package com.wu.controller;


import com.alibaba.druid.sql.ast.statement.SQLForeignKeyImpl;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wu.entity.User;
import com.wu.service.UserService;
import com.wu.utils.JWTUtils;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/login/{name}/{age}")
    @ResponseBody
    public Map<String,Object> login(User user){
        HashMap<String, Object> map = new HashMap<>();
        try{
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("name",user.getName());
            queryWrapper.eq("age",user.getAge());
            User user1 = userService.getOne(queryWrapper);
            Map<String, String> payload = new HashMap<>();
            payload.put("id", String.valueOf(user1.getId()));
            payload.put("name",user1.getName());
            //生成令牌
            String token = JWTUtils.getToken(payload);
            map.put("state",true);
            map.put("msg","成功登录!!");
            map.put("token",token);
        }catch (Exception e){
            map.put("state",false);
            map.put("msg",e.getMessage());
        }
        return map;
    }
//我们要让所有的接口都实现拦截功能，就需要一个拦截器handler包

    @GetMapping("/test")
    public Map<String,Object> test(HttpServletRequest request){

        HashMap<String , Object> map = new HashMap<>();
        //处理自己的业务逻辑,我们的token中包含一些信息，我们可以将它取出来
        String token = request.getHeader("token");
        DecodedJWT verify = JWTUtils.verify(token);
        log.info("id",verify.getClaim("id").asString());
        log.info("name",verify.getClaim("name").asString());
        map.put("state",true);
        map.put("msg","请求成功");
        return map;
    }























}
